﻿using System;
using System.Web;
using System.Web.UI;
using Newtonsoft.Json.Linq;

namespace Orbitone.MeetingRooms.RoomFinder
{
    public partial class Callback : Page
    {
        private readonly TokenRestApi TokenRestApi = new TokenRestApi();

        protected void Page_Load(object sender, EventArgs e)
        {
            HttpRequest request = Page.Request;
            string code = request.QueryString.Get("code");
            JObject tokens;
            if (!string.IsNullOrEmpty(code))
            {
                tokens = TokenRestApi.getTokens(Globals.APP_CLIENT_ID, Globals.APP_REDIRECT_URI,
                                                Globals.APP_CLIENT_SECRET, null, code);
                if (tokens == null)
                {
                    throw new Exception("Error retrieving tokens. Code execution has stopped.");
                }
            }
            else
            {
                throw new Exception(
                    "Error retrieving authorization code, likely due to malformed or missing URL parameter \'code\'. Code execution has stopped.");
            }

            var accessToken = (string) tokens["access_token"];
            JObject results = TokenRestApi.callRestApi(accessToken, Globals.REST_PATH_ME, Globals.REST_API_GET, null,
                                                       null);

            if (results == null)
            {
                throw new Exception("Error calling REST API. Code execution has stopped.");
            }
            else
            {
                //save token for future use
                JToken refreshToken = tokens["refresh_token"];

                Response.Cookies[Globals.COOKIE_NAME]["accessToken"] = accessToken;
                Response.Cookies[Globals.COOKIE_NAME]["id"] = (string) results["id"];
                Response.Cookies[Globals.COOKIE_NAME]["name"] = (string) results["name"];
            }

            Response.Redirect("~/Calendar.aspx");
        }
    }
}